package com.talos.ums.service.resource;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.resource.vo.UmsResourcePageReqVO;
import com.talos.ums.controller.admin.resource.vo.UmsResourceSaveReqVO;
import com.talos.ums.dal.dataobject.resource.UmsResourceDO;
import com.talos.ums.dal.mysql.resource.UmsResourceMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 资源表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsResourceServiceImpl implements UmsResourceService {

    @Resource
    private UmsResourceMapper resourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createResource(UmsResourceSaveReqVO createReqVO) {
        // 插入
        UmsResourceDO resource = BeanUtils.toBean(createReqVO, UmsResourceDO.class);
        resourceMapper.insert(resource);
        // 返回
        return resource.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateResource(UmsResourceSaveReqVO updateReqVO) {
        // 校验存在
        validateResourceExists(updateReqVO.getId());
        // 更新
        UmsResourceDO updateObj = BeanUtils.toBean(updateReqVO, UmsResourceDO.class);
        resourceMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteResource(Long id) {
        // 校验存在
        validateResourceExists(id);
        // 删除
        resourceMapper.deleteById(id);
    }

    private void validateResourceExists(Long id) {
        if (resourceMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsResourceDO getResource(Long id) {
        return resourceMapper.selectById(id);
    }

    @Override
    public PageResult<UmsResourceDO> getResourcePage(UmsResourcePageReqVO pageReqVO) {
        return resourceMapper.selectPage(pageReqVO);
    }

}
